package com.sec.android.app.myfiles.provider;

import android.content.BroadcastReceiver;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;

import com.sec.android.app.myfiles.info.AppFeatures;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.ModuleLoader;
import com.sec.android.app.myfiles.module.abstraction.AbsProviderImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;

import java.text.Collator;

public class PrivateMyFilesProvider extends ContentProvider {
    private static final String TAG = PrivateMyFilesProvider.class.getSimpleName();

    public static final String DATABASE_NAME = "privateMyfiles.db";
    public static final int DATABASE_VERSION = 307;

    private Context mContext;
    private static AbsProviderImp sProviderImp;

    public static void refreshDb(Context context, FileRecord curRecord) {
        Log.i(TAG, "refreshDb");
        refreshDb(context, curRecord, false);
    }

    public static void refreshDb(Context context, FileRecord curRecord, Boolean isForced) {
        if (curRecord == null) {
            return;
        }
        AbsProviderImp providerImp = getProviderImp(context);
        DbTableInfo tableInfo = ModuleLoader.getInstance().getTableInfo(curRecord.getStorageType());

        if (tableInfo != null) {
            providerImp.refreshDB(Uri.parse(tableInfo.getUri()), curRecord, isForced);
        }
    }

    public static void clearCache(Context context, FileRecord record) {

        AbsProviderImp providerImp = getProviderImp(context);

        if (record != null) {
            DbTableInfo tableInfo = ModuleLoader.getInstance().getTableInfo(record.getStorageType());

            if (tableInfo != null) {
                providerImp.clearCache(Uri.parse(tableInfo.getUri()), record);
            }
        } else {
            providerImp.clearCache(null, null);
        }

    }

    static AbsProviderImp getProviderImp(Context context) {
        if (sProviderImp == null) {
            sProviderImp = ModuleLoader.getInstance().createProviderImp(context);
        }

        return sProviderImp;
    }

    @Override
    public String getType(Uri arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean onCreate() {
        mContext = getContext();
        AppFeatures.initMode(mContext);
        sProviderImp = getProviderImp(mContext);

        MyFilesDBHelper helper = new MyFilesDBHelper(mContext);
        sProviderImp.setDB(helper.getWritableDatabase());
        sProviderImp.clearDB(helper.getWritableDatabase(), 0, DATABASE_VERSION);

        registerBroadcastReceiver();

        return false;
    }

    @Override
    public Cursor query(Uri uri, String[] projectionIn, String selection, String[] selectionArgs, String sortOrder) {
        Log.i(this, "query " + uri + "  selection:" + selection);
        return sProviderImp.query(uri, projectionIn, selection, selectionArgs, sortOrder);
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        return sProviderImp.insert(uri, values);
    }

    @Override
    public int bulkInsert(Uri uri, ContentValues[] values) {
        return sProviderImp.bulkInsert(uri, values);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        return sProviderImp.update(uri, values, selection, selectionArgs);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return sProviderImp.delete(uri, selection, selectionArgs);
    }

    private static class MyFilesDBHelper extends SQLiteOpenHelper {

        AbsProviderImp mProviderImp = null;

        public MyFilesDBHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            mProviderImp = PrivateMyFilesProvider.getProviderImp(context);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.i(this, "MyFilesDBHelper onCreate()");
            mProviderImp.updateDB(db, 0, DATABASE_VERSION);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.i(this, "updateDatabase() - oldVersion: " + oldVersion + ", newVersion: " + newVersion);
            if (oldVersion > newVersion) {
                throw new IllegalArgumentException();
            }

            if (oldVersion < DATABASE_VERSION) {
                mProviderImp.updateDB(db, oldVersion, newVersion);
            }
        }
    }

    private void registerBroadcastReceiver() {
        IntentFilter f = new IntentFilter();
        f.addAction(Intent.ACTION_LOCALE_CHANGED);
        getContext().registerReceiver(mBroadcastReceiver, f);
    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_LOCALE_CHANGED.equals(action)) {
                Collator.getInstance().setStrength(Collator.PRIMARY);
            }
        }
    };

    public static void stopRefreshDb(Context context, FileRecord.StorageType storageType) {
        AbsProviderImp providerImp = getProviderImp(context);
        DbTableInfo tableInfo = ModuleLoader.getInstance().getTableInfo(storageType);
        if (tableInfo != null) {
            providerImp.stopRefreshDb(Uri.parse(tableInfo.getUri()));
        }
    }
}
